from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional

from api.schemas.history import HistoryListResponse, HistoryDetailResponse
from db.database import get_db
from services.history_service import (
    get_compilation_history, get_compilation_history_detail,
    delete_compilation_history, clear_all_history
)
from loguru import logger

router = APIRouter()

@router.get("/", response_model=HistoryListResponse)
async def get_history(
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1, le=100),
    status: Optional[str] = Query(None, pattern="^(success|failed|processing|pending)$"),
    db: Session = Depends(get_db)
):
    """获取编译历史记录"""
    try:
        history_data = get_compilation_history(db, skip=skip, limit=limit, status=status)
        return history_data
    except Exception as e:
        logger.error(f"获取历史记录失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取历史记录失败: {str(e)}")

@router.get("/{task_id}", response_model=HistoryDetailResponse)
async def get_history_detail(task_id: str, db: Session = Depends(get_db)):
    """获取编译历史记录详情"""
    try:
        detail = get_compilation_history_detail(db, task_id)
        if not detail:
            raise HTTPException(status_code=404, detail="历史记录不存在")
        return detail
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取历史记录详情失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取历史记录详情失败: {str(e)}")

@router.delete("/{task_id}")
async def delete_history(task_id: str, db: Session = Depends(get_db)):
    """删除指定的历史记录"""
    try:
        result = delete_compilation_history(db, task_id)
        if not result:
            raise HTTPException(status_code=404, detail="历史记录不存在")
        return {"message": "历史记录已成功删除"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除历史记录失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"删除历史记录失败: {str(e)}")

@router.delete("/")
async def clear_history(db: Session = Depends(get_db)):
    """清空所有历史记录"""
    try:
        clear_all_history(db)
        return {"message": "所有历史记录已成功清空"}
    except Exception as e:
        logger.error(f"清空历史记录失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清空历史记录失败: {str(e)}")
